//
//  M4HomeSecondCell.swift
//  M4
//
//  Created by YuChuang on 2024/8/16.
//

import UIKit
import SDWebImage

class M4HomeSecondCell: M4BaseTableViewCell {
    
    @IBOutlet weak var M4HomeSecondTopView: UIView!
    
    @IBOutlet weak var M4HomeSecondLogo: UIImageView!
    
    @IBOutlet weak var M4HomeSecondName: UILabel!
    
    @IBOutlet weak var M4HomeSecondScore: UILabel!
    
    @IBOutlet weak var M4HomeSecondAmount: UILabel!
    
    @IBOutlet weak var M4HomeDays: UILabel!
    
    @IBOutlet weak var M4HSTimeView: UIView!
    
    @IBOutlet weak var M4HSTimeViewHeight: NSLayoutConstraint!
    
    @IBOutlet weak var M4HSTimeLabel: UILabel!
    
    @IBOutlet weak var M4HSCellButton: UIButton!
    
    @IBOutlet weak var M4HSCellAllButton: UIButton!
    
    @IBOutlet weak var lockImageView: UIImageView!
    
    @IBOutlet weak var lockTipLabel: UILabel!
    
    private var model: M4HomeProductModel?
    
    private var recommend: M4RecommendProsModel?
    
    private var M4HSCellTimer: Timer?
    
    private var M4HSCellRemainTime: Int = 0
    
    override func awakeFromNib() {
        super.awakeFromNib()
        M4HomeSecondTopView.backgroundColor = UIColor.init(white: 1, alpha: 0.8)
        
        lockTipLabel.text = "Una vez que se complete la solicitud del \nproducto desbloqueado, este producto se podrá \ndesbloquear rápidamente."
        lockTipLabel.numberOfLines = 0
    }
    
    override func M4UpdateDataAndUI() {//M4RecommendProsModel
        if data is M4HomeProductModel {
            model = data as? M4HomeProductModel
            M4HomeSecondName.text = model?.YKehcUmyK ?? ""
            M4HomeSecondLogo.sd_setImage(with: URL(string: model?.VirGg ?? ""))
            M4HomeSecondScore.text = model?.CzrFhiCi
            M4HomeSecondAmount.text = "＄\(M4String.M4BlankAmount(original: "\(model?.AeJZUX ?? 0)"))"
            M4HomeDays.text = "\(model?.XmIUctlz ?? 0) días"
            M4HSTimeView.isHidden = model?.kJdssdf ?? 0 > 0 ? false : true
            M4HSTimeViewHeight.constant = model?.kJdssdf ?? 0 > 0 ? 40 : 10
            if model?.kJdssdf ?? 0 > 0 {
                M4HSCellRemainTime = (model?.kJdssdf ?? 0) / 1000
                let timeStr = M4String.M4TimeStampToString(timeStamp: M4HSCellRemainTime)
                if M4HSCellTimer == nil {
                    M4HSCellTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.M4HSCellTimeCountDown), userInfo: nil, repeats: true)
                    RunLoop.main.add(M4HSCellTimer!, forMode: .common)
                }
                let fullText = "Se enviará la solicitud tras \(timeStr) >"
                let attributedString = NSMutableAttributedString(string: fullText)
                let timeRange = (fullText as NSString).range(of: "\(timeStr) >")
                let boldFont = UIFont.systemFont(ofSize: 12, weight: .medium)
                let largerFont = UIFont.systemFont(ofSize: 13, weight: .bold)
                attributedString.addAttribute(.font, value: boldFont, range: timeRange)
                attributedString.addAttribute(.font, value: largerFont, range: timeRange)
                M4HSTimeLabel.attributedText = attributedString
            }
            else {
                M4HSTimeLabel.text = ""
            }
            M4HomeSecondTopView.isHidden = true
            lockImageView.isHidden = true
            lockTipLabel.isHidden = true
            M4HSCellAllButton.M4EventUnavailable = false
            M4HSCellButton.backgroundColor = COLOR_00479D
            M4HSCellButton.setTitleColor(.white, for: .normal)
            //0首页 1认证中 2审核中 3审核通过 4审核被拒 5订单异常关闭 6放款失败 7正常待还 8逾期未还
            if model?.HRJAukei == 0 || model?.HRJAukei == 1 || model?.HRJAukei == 5 {
                M4HSCellButton.setTitle("  Solicitar ahora  ", for: .normal)
                if model?.TleRIb == 0 {//不可借
                    M4HomeSecondTopView.isHidden = false
                    M4HSCellAllButton.M4EventUnavailable = false//依然可以点击，弹框提示
                    lockImageView.isHidden = false
                    lockTipLabel.isHidden = false
                }
            }
            else if model?.HRJAukei == 2 {
                M4HSCellButton.setTitle("  En revisión  ", for: .normal)
            }
            else if model?.HRJAukei == 3 {
                M4HSCellButton.setTitle("  Aprobación  ", for: .normal)
            }
            else if model?.HRJAukei == 4 {
                M4HSCellButton.setTitle("  Préstamo denegado  ", for: .normal)
                M4HSCellButton.backgroundColor = COLOR_EEEEEE
                M4HSCellButton.setTitleColor(COLOR_9D0000, for: .normal)
            } else if model?.HRJAukei == 6 {
                M4HSCellButton.setTitle("  Transferencia falló  ", for: .normal)
            }
            else if model?.HRJAukei == 7 {
                M4HSCellButton.setTitle("  Pendiente de reembolso  ", for: .normal)
            }
            else if model?.HRJAukei == 8 {
                M4HSCellButton.setTitle("  Atrasado  ", for: .normal)
                M4HSCellButton.backgroundColor = COLOR_EEEEEE
                M4HSCellButton.setTitleColor(COLOR_9D0000, for: .normal)
            }
        }
        else if data is M4RecommendProsModel {
            recommend = data as? M4RecommendProsModel
            M4HomeSecondName.text = recommend?.YqHOjBd
            M4HomeSecondLogo.sd_setImage(with: URL(string: recommend?.DSXEx ?? ""))
            M4HomeSecondScore.text = recommend?.FHrBj
            M4HomeSecondAmount.text = "＄\(M4String.M4BlankAmount(original: "\(recommend?.OhfOKP ?? 0)"))"
            M4HSTimeView.isHidden = true
            M4HSTimeViewHeight.constant = 10
            M4HSTimeLabel.text = ""
            M4HomeSecondTopView.backgroundColor = .clear
            M4HSCellButton.setTitle("  Ir a descargar App  ", for: .normal)
            lockImageView.isHidden = true
            lockTipLabel.isHidden = true
        }
        
    }
    
    @objc private func M4HSCellTimeCountDown() {
        M4HSCellRemainTime -= 1
        if M4HSCellRemainTime <= 0 {
            M4HSCellStopTimer()
            M4CellActionDelegate?.M4CellAction(M4IDAction(actionType: M4HomeStatusAction.M4HomeSectionTimeEndAction.rawValue))
        }
        else {
            let timeStr = M4String.M4TimeStampToString(timeStamp: M4HSCellRemainTime)
            let fullText = "Se enviará la solicitud tras \(timeStr) >"
            let attributedString = NSMutableAttributedString(string: fullText)
            let timeRange = (fullText as NSString).range(of: "\(timeStr) >")
            let boldFont = UIFont.systemFont(ofSize: 12, weight: .medium)
            let largerFont = UIFont.systemFont(ofSize: 13, weight: .bold)
            attributedString.addAttribute(.font, value: boldFont, range: timeRange)
            attributedString.addAttribute(.font, value: largerFont, range: timeRange)
            M4HSTimeLabel.attributedText = attributedString
        }
    }
    
    private func M4HSCellStopTimer() {
        M4HSCellTimer?.invalidate()
        M4HSCellTimer = nil
        M4HSCellRemainTime = 0
    }
    

    @IBAction func M4HSCellButtonClick(_ sender: UIButton) {
        if data is M4HomeProductModel {
            M4CellActionDelegate?.M4CellAction(M4IDAction(actionType: M4HomeStatusAction.M4HomeSecondAction.rawValue, actionData: model))
        }
        else if data is M4RecommendProsModel {
            M4CellActionDelegate?.M4CellAction(M4IDAction(actionType: M4LoanResultAction.M4RecommendProAction.rawValue, actionData: recommend?.VPkbCXJc))
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now()+2) {
            sender.M4EventUnavailable = false
        }
    }
    
    
}
